﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Metadata.Entity.Page;
using T.ServiceComponent.DAC.Service;
using T.ServiceComponent.DataAccessEx.Core;
using T.ServiceComponent.Database.Service;

namespace T.FAS.Runtime.Page.Dao
{
    public class PageTemplateDao : DaoService<PageTemplate>
    {
        public PageTemplateDao() :
           base()
        {
            DBName = "TFAS";
        }

        public override string TableName => "FAS_PageTemplate";
        public override string IDColumnName => "ID";
        public override List<string> ExceptColumnName => new List<string> { "PageMetaData", "TemplateReplaceDefines" };
        public override Dictionary<string, object> GetDataMapping(PageTemplate data)
        {
            var datas = base.GetDataMapping(data);
            datas.Remove("TemplateType");
            datas.Add("TemplateType", (int)(data.TemplateType));
            datas.Remove("EngineType");
            datas.Add("EngineType", (int)(data.EngineType));
            datas.Remove("ClientType");
            datas.Add("ClientType", (int)(data.ClientType));
            datas.Remove("PageType");
            datas.Add("PageType", (int)(data.PageType));
            datas.Remove("PageDetailType");
            datas.Add("PageDetailType", (int)(data.PageDetailType));
            return datas;
        }
        public override PageTemplate ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            var myCol = new Dictionary<string, PropertyInfo>(base.Columns);
            myCol.Remove("TemplateType");
            myCol.Remove("ClientType");
            myCol.Remove("PageType");
            myCol.Remove("EngineType");
            myCol.Remove("PageDetailType");
            var data = base.ConvertToObject(myCol, row);
            if (row["TemplateType"] != DBNull.Value)
                data.TemplateType = (TemplateType)Enum.Parse(typeof(TemplateType),
                                                Convert.ToString(row["TemplateType"]));
            if (row["ClientType"] != DBNull.Value)
                data.ClientType = (ClientType)Enum.Parse(typeof(ClientType),
                                                Convert.ToString(row["ClientType"]));
            if (row["EngineType"] != DBNull.Value)
                data.EngineType = (EngineType)Enum.Parse(typeof(EngineType),
                                                Convert.ToString(row["EngineType"]));
            if (row["PageType"] != DBNull.Value)
                data.PageType = (PageType)Enum.Parse(typeof(PageType),
                                                Convert.ToString(row["PageType"]));
            if (row["PageDetailType"] != DBNull.Value)
                data.PageDetailType = (PageDetailType)Enum.Parse(typeof(PageDetailType),
                                                Convert.ToString(row["PageDetailType"]));
            return data;
        }
        /// <summary>
        /// 获取Page模板名称是否存在
        /// </summary>
        /// <param name="templateGroupID"></param>
        /// <param name="Name"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int CheckPageTemplateNameExist(string templateGroupID, string Name, string ID)
        {

            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(DB.MakeInParam("@templateGroupID", TDbDataType.VarChar, templateGroupID));
            paramsList.Add(DB.MakeInParam("@Name", TDbDataType.VarChar, Name));
            string sql = $"select Name FROM {TableName} WHERE TemplateGroupID=@templateGroupID and Name =@Name ";
            if (!string.IsNullOrEmpty(ID))
            {
                paramsList.Add(DB.MakeInParam("@ID", TDbDataType.VarChar, ID));
                sql += $"and ID !=@ID ";
            }
            int count;
            var result = DB.ExecuteScalar(sql, paramsList.ToArray());
            if (int.TryParse(Convert.ToString(result), out count))
            {
                return count;
            }
            return 0;
        }
        /// <summary>
        /// 获取分组模板
        /// </summary>
        /// <param name="templateGroupID"></param>
        /// <param name="projectID"></param>
        /// <returns></returns>
        public List<PageTemplate> GetPageTemplates(string templateGroupID, string projectID, int engineType)
        {
            var result = new List<PageTemplate>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@templateGroupID", TDbDataType.VarChar, templateGroupID));
            paramList.Add(DB.MakeInParam("@engineType", TDbDataType.Int, engineType));
            paramList.Add(DB.MakeInParam("@tenantID", TDbDataType.VarChar, UserUtil.GetCurrentUserTenantId()));
            paramList.Add(DB.MakeInParam("@projectID", TDbDataType.VarChar, projectID));
            paramList.Add(DB.MakeInParam("@UserID", TDbDataType.VarChar, UserUtil.GetCurrentUserID()));
            PageTemplateGroupDao groupDao = new PageTemplateGroupDao();
            PageTemplateGroup templateGroup = groupDao.GetObject(templateGroupID);
            string sql = $"select * from {TableName} where TemplateGroupID=@templateGroupID and engineType =@engineType and tenantID =@tenantID ";
            if (templateGroup != null)
            {
                switch (templateGroup.TemplateType)
                {
                    case TemplateType.System:
                        sql = $"{sql} and TemplateType = 0 ";
                        break;
                    case TemplateType.Project:
                        sql = $"{sql} and TemplateType = 1 and projectID =@projectID ";
                        break;
                    case TemplateType.Self:
                        sql = $"{sql} and TemplateType = 2 and UserID =@UserID ";
                        break;
                }
            }
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    result.Add(ConvertToObject(Columns, row));
                }
            }
            return result.OrderBy(t => t.SortOrder).ToList();
        }
        /// <summary>
        /// 获取模板分组
        /// </summary>
        /// <param name="templateGroupID"></param>
        /// <param name="projectID"></param>
        /// <returns></returns>
        public List<PageTemplate> GetPageTemplates(string templateGroupID, int pageType, int templateType, int clientType, int engineType)
        {
            var result = new List<PageTemplate>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@templateGroupID", TDbDataType.VarChar, templateGroupID));
            paramList.Add(DB.MakeInParam("@tenantID", TDbDataType.VarChar, UserUtil.GetCurrentUserTenantId()));
            paramList.Add(DB.MakeInParam("@engineType", TDbDataType.Int, engineType));
            paramList.Add(DB.MakeInParam("@clientType", TDbDataType.Int, clientType));
            paramList.Add(DB.MakeInParam("@pageType", TDbDataType.Int, pageType));
            paramList.Add(DB.MakeInParam("@templateType", TDbDataType.Int, templateType));
            string sql = $"select * from {TableName} where TemplateGroupID=@templateGroupID and TemplateType =@templateType and engineType =@engineType and tenantID =@tenantID and clientType=@clientType ";
            if (pageType != 0)
            {
                sql = sql + $" and pageType=@pageType ";
            }
            else
            {
                sql = sql + $" and pageType not in (7,8,9) ";
            }
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    result.Add(ConvertToObject(Columns, row));
                }
            }
            return result.OrderBy(t => t.SortOrder).ToList();
        }
        /// <summary>
        /// 获取系统模板
        /// </summary>
        /// <returns></returns>
        public List<PageTemplate> GetSystemPageTemplate(int engineType)
        {
            var result = new List<PageTemplate>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@engineType", TDbDataType.Int, engineType));
            string sql = $"select * from {TableName} where TemplateType = 0 and CanOneClick = 1 and engineType=@engineType ";
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    result.Add(ConvertToObject(Columns, row));
                }
            }
            return result.OrderBy(t => t.SortOrder).ToList();
        }
    }
}
